<!DOCTYPE html>


<html lang="en">
  

    <head>
      <meta charset="utf-8" />
        
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>《JavaScript高级程序设计》- 第九章：代理与反射 |  欢迎</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="欢迎" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-JavaScript学习/《JavaScript高级程序设计》- 第九章：代理与反射"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  《JavaScript高级程序设计》- 第九章：代理与反射
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/02/22/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E4%B9%9D%E7%AB%A0%EF%BC%9A%E4%BB%A3%E7%90%86%E4%B8%8E%E5%8F%8D%E5%B0%84/" class="article-date">
  <time datetime="2022-02-21T16:26:34.000Z" itemprop="datePublished">2022-02-22</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/JavaScript%E5%AD%A6%E4%B9%A0/">JavaScript学习</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">3.5k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">15 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="第九章：代理与反射"><a href="#第九章：代理与反射" class="headerlink" title="第九章：代理与反射"></a>第九章：代理与反射</h2><p>ES6中新增的代理与反射：提供了<code>拦截</code>并<code>向基本操作嵌入额外行为</code>的能力；具体的实现方式就是：通过一个给<code>目标对象</code>定义一个关联的<code>代理对象</code>，通过<code>代理对象</code>内部的操作对<code>目标对象</code>的操作加以<code>控制</code></p>
<blockquote>
<p>注意：代理和反射只在百分百支持它们的平台上有用</p>
</blockquote>
<h3 id="9-1-代理基础"><a href="#9-1-代理基础" class="headerlink" title="9.1 代理基础"></a>9.1 代理基础</h3><p>从很多方面看，<code>代理</code>类似<code>C++的指针</code>，可以用作对象的替身；当然，目标对象既可以直接操作（会绕过代理）、也可以通过代理来操作。</p>
<h4 id="9-1-1-代理创建"><a href="#9-1-1-代理创建" class="headerlink" title="9.1.1 代理创建"></a>9.1.1 代理创建</h4><p>通过<code>Proxy</code>构造函数创建，其接收两个参数：</p>
<ul>
<li>目标对象</li>
<li>处理程序对象</li>
</ul>
<p>两个参数是<code>必需</code>的；缺一个就会报错。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建目标对象</span></span><br><span class="line"><span class="keyword">const</span> targetObject = &#123;</span><br><span class="line">	<span class="attr">name</span>:<span class="string">&#x27;target&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 创建空处理程序对象</span></span><br><span class="line"><span class="keyword">const</span> handler = &#123; <span class="comment">/* 对数据进行一些操作（捕获器） */</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(targetObject,handler);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 给目标对象赋值 会反映在两个对象上</span></span><br><span class="line">targetObject.name = <span class="string">&#x27;hello&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(targetObject.name);		<span class="comment">//hello</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy.name);			<span class="comment">//hello</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 給代理对象赋值 也会反映在两个对象上</span></span><br><span class="line">proxy.name = <span class="string">&#x27;world&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(targetObject.name);		<span class="comment">//world</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy.name);			<span class="comment">//world</span></span><br></pre></td></tr></table></figure>



<h4 id="9-1-2-定义捕获器"><a href="#9-1-2-定义捕获器" class="headerlink" title="9.1.2 定义捕获器"></a>9.1.2 定义捕获器</h4><p>使用代理的<strong>主要目的</strong>是<code>定义捕获器</code>；</p>
<ul>
<li>捕获器：处理程序对象中定义的“基本操作的拦截器”；</li>
<li>每个程序可以包括<code>0个或多个</code>；</li>
<li>每个捕获器对应一种<code>基本操作</code>，可以<code>直接</code>或<code>间接</code>在代理对象上调用；</li>
</ul>
<p>每次在<code>代理对象</code>上调用这些<code>基本操作</code>的时候，<code>代理</code>可以在这些操作传播到目标对象之前先调用捕获器函数，从而拦截并修改相应的行为。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> targetObject = &#123;</span><br><span class="line">    <span class="attr">name</span>:<span class="string">&#x27;target&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> handler = &#123;</span><br><span class="line">    <span class="function"><span class="title">get</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;hello world!&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(targetObject,handler);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(targetObject.name);     <span class="comment">// target</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy.name);            <span class="comment">// hello world!</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>显然，直接操作对象，会绕过代理器</p>
</blockquote>
<h4 id="9-1-3-捕获器参数-结合-反射API"><a href="#9-1-3-捕获器参数-结合-反射API" class="headerlink" title="9.1.3 捕获器参数 结合 反射API"></a>9.1.3 捕获器参数 结合 反射API</h4><p>所有捕获器都可以访问<code>相应的参数</code>，可以基于这些<code>参数</code><strong>重建</strong>被捕获方法的原始行为。一般参数如下：</p>
<ul>
<li>trapTarget：被捕获的目标对象</li>
<li>property：属性</li>
<li>value：值</li>
<li>receiver：代理程序对象</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> targetObject = &#123;</span><br><span class="line">    <span class="attr">name</span>:<span class="string">&#x27;target&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> handler = &#123;</span><br><span class="line">    <span class="function"><span class="title">get</span>(<span class="params">trapTarget,property,receiver</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(trapTarget);        <span class="comment">// &#123; name:&#x27;target&#x27; &#125;</span></span><br><span class="line">        <span class="built_in">console</span>.log(property);          <span class="comment">// name</span></span><br><span class="line">        <span class="built_in">console</span>.log(receiver);          <span class="comment">// &#123; name:&#x27;target&#x27; &#125;</span></span><br><span class="line">        <span class="keyword">return</span> targetObject[name];	<span class="comment">// 如果不返回，则标识返回undefined</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(targetObject,handler);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(targetObject.name);     <span class="comment">// target</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy.name);            <span class="comment">// target</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>实际上，并不需要开发者手动重建原始行为，而可以通过<code>全局Reflect</code>对象的同名方法来进行重建。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> targetObject = &#123;</span><br><span class="line">    <span class="attr">name</span>:<span class="string">&#x27;target&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> handler = &#123;</span><br><span class="line">    <span class="function"><span class="title">get</span>(<span class="params">trapTarget,property,receiver</span>)</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">Reflect</span>.get(...arguments);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(targetObject,handler);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(targetObject.name);     <span class="comment">// target</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy.name);            <span class="comment">// target</span></span><br></pre></td></tr></table></figure>
</blockquote>
<p>显然，上面只是创建了<code>所有属性</code>的捕获方法，一般实际情况会如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> targetObject = &#123;</span><br><span class="line">    <span class="attr">id</span>:<span class="number">1</span>,</span><br><span class="line">    <span class="attr">name</span>:<span class="string">&#x27;target&#x27;</span>,</span><br><span class="line">    <span class="attr">addr</span>:<span class="string">&#x27;天堂&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> handler = &#123;</span><br><span class="line">    <span class="function"><span class="title">get</span>(<span class="params">trapTarget,property,receiver</span>)</span> &#123;</span><br><span class="line">		<span class="keyword">let</span> decoration = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">        <span class="keyword">if</span>( trapTarget[property] === <span class="string">&#x27;天堂&#x27;</span> )&#123;</span><br><span class="line">            decoration = <span class="string">&quot;上帝的邻居：&quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> decoration + <span class="built_in">Reflect</span>.get(...arguments);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(targetObject,handler);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(proxy.name);        <span class="comment">// target</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy.addr);        <span class="comment">// 上帝的邻居：天堂</span></span><br></pre></td></tr></table></figure>



<h4 id="9-1-4-捕获器不变式"><a href="#9-1-4-捕获器不变式" class="headerlink" title="9.1.4 捕获器不变式"></a>9.1.4 捕获器不变式</h4><blockquote>
<p>个人理解：捕获器也需要遵循一定的规则</p>
<p>当属性<code>不可配置</code>或<code>不可写入</code>的时候，不可进行操作</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> target = &#123;&#125;</span><br><span class="line"><span class="built_in">Object</span>.defineProperty(target, <span class="string">&#x27;sex&#x27;</span> , &#123;</span><br><span class="line"> <span class="attr">configurable</span>: <span class="literal">false</span>,</span><br><span class="line"> <span class="attr">writable</span>:<span class="literal">false</span>,</span><br><span class="line"> <span class="attr">value</span>:<span class="string">&#x27;male&#x27;</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> handler = &#123;</span><br><span class="line"> <span class="function"><span class="title">get</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">     <span class="keyword">return</span> <span class="string">&#x27;female&#x27;</span></span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(target,handler);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(proxy.sex);     <span class="comment">// 报错TypeError</span></span><br></pre></td></tr></table></figure>
</blockquote>
<h4 id="9-1-5-撤销代理"><a href="#9-1-5-撤销代理" class="headerlink" title="9.1.5 撤销代理"></a>9.1.5 撤销代理</h4><p>除了使用<code>Proxy</code>的构造函数创建代理之外，<code>Proxy</code>还暴露了<code>revocable()</code>和<code>revoke()</code>分别用于关联和撤销代理。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> target = &#123;</span><br><span class="line">    <span class="attr">id</span>:<span class="number">1</span>,</span><br><span class="line">    <span class="attr">name</span>:<span class="string">&#x27;zyzc&#x27;</span>,</span><br><span class="line">    <span class="attr">title</span>:<span class="string">&#x27;hello&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> handler = &#123;</span><br><span class="line">    <span class="function"><span class="title">get</span>(<span class="params">trapObject,property,receiver</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Reflect</span>.get(...arguments);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> &#123; proxy , revoke &#125; = <span class="built_in">Proxy</span>.revocable(target,handler);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(proxy.name);		<span class="comment">// zyzc</span></span><br><span class="line">revoke();</span><br><span class="line"><span class="built_in">console</span>.log(proxy.name)			<span class="comment">// Cannot perform &#x27;get&#x27; on a proxy that has been revoked</span></span><br></pre></td></tr></table></figure>



<h4 id="9-1-6-反射的特点、优点"><a href="#9-1-6-反射的特点、优点" class="headerlink" title="9.1.6 反射的特点、优点"></a>9.1.6 反射的特点、优点</h4><p>在某些情况下，应该优先使用反射API：</p>
<ol>
<li><p>反射API 与 对象API对比</p>
<ul>
<li>大多数反射API在Object类型上有对应的方法：通常，Object上的方法适用于<strong>通用程序</strong>，反射方法适用于<strong>细粒度的对象控制与操作</strong></li>
</ul>
</li>
<li><p>状态标记</p>
<p>很多反射方法会返回称作<code>状态标记</code>的布尔值，表示意图执行的操作是否成功。这些方法有：</p>
<ul>
<li><code>Reflect.defineProperty()</code></li>
<li><code>Reflect.preventExtensions()</code></li>
<li><code>Reflect.setPrototypeOf()</code></li>
<li><code>Reflect.set()</code></li>
<li><code>Reflect.deleteProperty()</code></li>
</ul>
<p>使用反射API，可以重构那些：返回修改后对象、抛出错误的方法。</p>
<blockquote>
<p>初始代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> object = &#123;&#125;;</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="built_in">Object</span>.defineProperty(object,<span class="string">&#x27;name&#x27;</span>,<span class="string">&#x27;zyzc&#x27;</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;success&#x27;</span>);</span><br><span class="line">&#125;<span class="keyword">catch</span>(e)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;failure&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>反射API重构之后：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> object = &#123;&#125;;</span><br><span class="line"><span class="keyword">if</span>(<span class="built_in">Reflect</span>.defineProperty(object,<span class="string">&#x27;name&#x27;</span>,<span class="string">&#x27;zyzc&#x27;</span>))&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;success&#x27;</span>);</span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;failure&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></blockquote>
</li>
<li><p>一等函数代替操作符</p>
<ul>
<li><code>Reflect.get()</code>：代替属性访问操作符</li>
<li><code>Reflect.set()</code>：代替赋值操作符</li>
<li><code>Reflect.has()</code>：代替in或with()</li>
<li><code>Reflect.deleteProperty()</code>：代替delete</li>
<li><code>Reflect.construct()</code>：代替new</li>
</ul>
</li>
<li><p>安全地应用函数</p>
<p>在几乎不可能的情况下，当方法名apply和属性名apply一致的时候，可以使用<code>Reflect.apply()</code>来代替。</p>
</li>
</ol>
<h4 id="9-1-7-代理另一个代理"><a href="#9-1-7-代理另一个代理" class="headerlink" title="9.1.7 代理另一个代理"></a>9.1.7 代理另一个代理</h4><p>可以使用一个代理，代理另一个代理，构建多层拦截网</p>
<h4 id="9-1-8-代理的不足"><a href="#9-1-8-代理的不足" class="headerlink" title="9.1.8 代理的不足"></a>9.1.8 代理的不足</h4><p>很大程度上，代理作为<code>对象的虚拟层</code>可以正常使用。但是有时候并不完美；</p>
<ol>
<li><p>代理的this</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> target = &#123;</span><br><span class="line">    <span class="function"><span class="title">show</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span> === proxy</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(target,&#123;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(target.show());	<span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy.show());	<span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>这样没什么问题，如果遇到了依赖的实例对象标识，就会出现如下问题：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> wm = <span class="keyword">new</span> <span class="built_in">WeakMap</span>();</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">userId</span>)</span>&#123;</span><br><span class="line">        wm.set(<span class="built_in">this</span>,userId);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">set</span> <span class="title">id</span>(<span class="params">userId</span>)&#123;</span><br><span class="line">        wm.set(<span class="built_in">this</span>,userId);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">get</span> <span class="title">id</span>()&#123;</span><br><span class="line">        <span class="keyword">return</span> wm.get(<span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> user = <span class="keyword">new</span> User(<span class="number">123</span>);</span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(user,&#123;&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(user.id);	<span class="comment">// 123;</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy.id);	<span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>

<p>需要这样操作！【个人感觉没什么用….】</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> wm = <span class="keyword">new</span> <span class="built_in">WeakMap</span>();</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">userId</span>)</span>&#123;</span><br><span class="line">        wm.set(<span class="built_in">this</span>,userId);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">set</span> <span class="title">id</span>(<span class="params">userId</span>)&#123;</span><br><span class="line">        wm.set(<span class="built_in">this</span>,userId);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">get</span> <span class="title">id</span>()&#123;</span><br><span class="line">        <span class="keyword">return</span> wm.get(<span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> userClassProxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(User,&#123;&#125;);</span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> userClassProxy(<span class="number">123</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(proxy.id);	<span class="comment">// 123</span></span><br></pre></td></tr></table></figure></li>
<li><p>代理与内部槽位</p>
<p>代理与内置引用类型的实例，一般可以协同，但是有一些内置类型可能会<code>依赖代理无法控制的机制</code>。</p>
<blockquote>
<p>比如说<code>Date</code>：<code>Date</code>类型方法的执行，依赖<code>this</code>值上的内部槽位<code>[[NumberDate]]</code>，但是<code>代理对象</code>并不存在这个槽位，而且内部槽位的值<strong>不能</strong>通过普通的<code>get()</code>和<code>set()</code>操作。所以当代理拦截后，本应转发给目标对象的方法，会抛出<code>TypeError</code></p>
</blockquote>
</li>
</ol>
<h3 id="9-2-代理捕获器与反射方法"><a href="#9-2-代理捕获器与反射方法" class="headerlink" title="9.2 代理捕获器与反射方法"></a>9.2 代理捕获器与反射方法</h3><blockquote>
<p>介绍前几种,其他的类似就不一一叙述</p>
</blockquote>
<h4 id="9-2-1-get"><a href="#9-2-1-get" class="headerlink" title="9.2.1 get()"></a>9.2.1 get()</h4><blockquote>
<p><code>get()</code>捕获器在获取属性值的操作中被调用。</p>
<ul>
<li>返回值<ul>
<li>没有返回值限制</li>
</ul>
</li>
<li>拦截的操作<ul>
<li><code>proxy.property</code></li>
<li><code>proxy[property]</code></li>
<li><code>Object.create(proxy)[property]</code></li>
<li><code>Reflect.get(proxy, property, receiver)</code></li>
</ul>
</li>
<li>捕获器处理程序参数<ul>
<li>target：目标对象</li>
<li>property：引用的目标对象上的字符串键属性。  </li>
<li>receiver：代理对象或继承代理对象的对象  </li>
</ul>
</li>
<li>捕获器不变式<ul>
<li>如果<code>target.property</code>不可写且不可配置， 则处理程序返回的值必须与<code>target.property</code>匹配。 </li>
<li>如果<code>target.property</code>不可配置且<code>[[Get]]</code>特性为<code>undefined</code>， 处理程序的返回值也必须是<code>undefined</code>。  </li>
</ul>
</li>
</ul>
</blockquote>
<h4 id="9-2-2-set"><a href="#9-2-2-set" class="headerlink" title="9.2.2 set()"></a>9.2.2 set()</h4><blockquote>
<p><code>set()</code>捕获器设置属性值的操作中被调用。</p>
<ul>
<li>返回值<ul>
<li>true</li>
<li>false【严格模式下抛出错误】</li>
</ul>
</li>
<li>拦截的操作<ul>
<li><code>proxy.property = value</code></li>
<li><code>proxy[property] = value</code></li>
<li><code>Object.create(proxy)[property] = value</code></li>
<li><code>Reflect.set(proxy, property, value, receiver)  </code></li>
</ul>
</li>
<li>捕获器处理程序参数<ul>
<li>target： 目标对象。</li>
<li>property： 引用的目标对象上的字符串键属性。</li>
<li>value： 要赋给属性的值。</li>
<li>receiver： 接收最初赋值的对象。  </li>
</ul>
</li>
<li>捕获器不定式<ul>
<li>如果<code>target.property</code>不可写且不可配置， 则不能修改目标属性的值。</li>
<li>如果<code>target.property</code>不可配置且<code>[[Set]]</code>特性为<code>undefined</code>， 则不能修改目标属性的值。</li>
<li>在严格模式下， 处理程序中返回false会抛出<code>TypeError</code></li>
</ul>
</li>
</ul>
</blockquote>
<h4 id="9-2-3-has"><a href="#9-2-3-has" class="headerlink" title="9.2.3 has()"></a>9.2.3 has()</h4><blockquote>
<p><code>has()</code>捕获器会在<code>in</code>操作符中被调用。</p>
<ul>
<li>返回值【表示是否存在】<ul>
<li>true</li>
<li>false</li>
</ul>
</li>
<li>拦截的操作<ul>
<li><code>property in proxy</code></li>
<li><code>property in Object.create(proxy)</code></li>
<li><code>with(proxy) &#123;(property);&#125;</code></li>
<li><code>Reflect.has(proxy, property)  </code></li>
</ul>
</li>
<li>捕获器处理程序参数<ul>
<li>target： 目标对象。</li>
<li>property： 引用的目标对象上的字符串键属性。  </li>
</ul>
</li>
<li>捕获器不变式<ul>
<li>如果<code>target.property</code>存在且不可配置， 则处理程序必须返回<code>true</code>。</li>
<li>如果<code>target.property</code>存在且目标对象不可扩展， 则处理程序必须返回<code>true</code>。  </li>
</ul>
</li>
</ul>
</blockquote>
<h4 id="9-2-4-defineProperty"><a href="#9-2-4-defineProperty" class="headerlink" title="9.2.4 defineProperty()"></a>9.2.4 defineProperty()</h4><blockquote>
<p><code>defineProperty()</code>捕获器会在<code>Object.defineProperty()</code>中被调用。  </p>
<ul>
<li>返回值【表示是否定义成功】<ul>
<li>true</li>
<li>false</li>
</ul>
</li>
<li>拦截的操作<ul>
<li><code>Object.defineProperty(proxy, property, descriptor)</code></li>
<li><code>Reflect.defineProperty(proxy, property, descriptor)  </code></li>
</ul>
</li>
<li>捕获器处理程序参数<ul>
<li>target： 目标对象。</li>
<li>property： 引用的目标对象上的字符串键属性。</li>
<li>descriptor： 包含可选的enumerable、 configurable、 writable、 value、 get和set定义的对象  </li>
</ul>
</li>
<li>捕获器不变式<ul>
<li>如果目标对象不可扩展， 则无法定义属性</li>
<li>如果目标对象有一个可配置的属性， 则不能添加同名的不可配置属性</li>
<li>如果目标对象有一个不可配置的属性， 则不能添加同名的可配置属性  </li>
</ul>
</li>
</ul>
</blockquote>
<h4 id="9-2-5-getOwnPropertyDescriptor"><a href="#9-2-5-getOwnPropertyDescriptor" class="headerlink" title="9.2.5 getOwnPropertyDescriptor()"></a>9.2.5 getOwnPropertyDescriptor()</h4><h4 id="9-2-6-deleteProperty"><a href="#9-2-6-deleteProperty" class="headerlink" title="9.2.6 deleteProperty()"></a>9.2.6 deleteProperty()</h4><h4 id="9-2-7-ownKeys"><a href="#9-2-7-ownKeys" class="headerlink" title="9.2.7 ownKeys()"></a>9.2.7 ownKeys()</h4><h4 id="9-2-8-getPrototypeOf"><a href="#9-2-8-getPrototypeOf" class="headerlink" title="9.2.8 getPrototypeOf()"></a>9.2.8 getPrototypeOf()</h4><h4 id="9-2-9-setPrototypeOf"><a href="#9-2-9-setPrototypeOf" class="headerlink" title="9.2.9 setPrototypeOf()"></a>9.2.9 setPrototypeOf()</h4><h4 id="9-2-10-isExtensible"><a href="#9-2-10-isExtensible" class="headerlink" title="9.2.10 isExtensible()"></a>9.2.10 isExtensible()</h4><h4 id="9-2-11-preventExtensions"><a href="#9-2-11-preventExtensions" class="headerlink" title="9.2.11 preventExtensions()"></a>9.2.11 preventExtensions()</h4><h4 id="9-2-12-apply"><a href="#9-2-12-apply" class="headerlink" title="9.2.12 apply()"></a>9.2.12 apply()</h4><blockquote>
<p>在函数被调用的时候捕获</p>
<ul>
<li>返回值<ul>
<li>返回值无限制</li>
</ul>
</li>
<li>拦截的操作<ul>
<li><code>proxy(...argumentsList)</code></li>
<li><code>Function.prototype.apply(thisArg, argumentsList)</code></li>
<li><code>Function.prototype.call(thisArg, ...argumentsList)</code></li>
<li><code>Reflect.apply(target, thisArgument, argumentsList)  </code></li>
</ul>
</li>
<li>捕获器处理程序参数<ul>
<li>target： 目标对象。</li>
<li>thisArg： 调用函数时的this参数。</li>
<li>argumentsList： 调用函数时的参数列表  </li>
</ul>
</li>
<li>捕获器不变式<ul>
<li>target必需是一个对象</li>
</ul>
</li>
</ul>
</blockquote>
<h4 id="9-2-13-construct"><a href="#9-2-13-construct" class="headerlink" title="9.2.13 construct()"></a>9.2.13 construct()</h4><h3 id="9-3-代理模式"><a href="#9-3-代理模式" class="headerlink" title="9.3 代理模式"></a>9.3 代理模式</h3><blockquote>
<p>可以利用代理，实现一些<code>编程模式</code></p>
</blockquote>
<h4 id="9-3-1-跟踪属性访问"><a href="#9-3-1-跟踪属性访问" class="headerlink" title="9.3.1 跟踪属性访问"></a>9.3.1 跟踪属性访问</h4><p>可以通过<code>get、set和has</code>操作，知道属性对象什么时候被访问、被查询；</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> user = &#123;</span><br><span class="line">    <span class="attr">name</span>:<span class="string">&#x27;zyzc&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(user, &#123;</span><br><span class="line">    <span class="function"><span class="title">get</span>(<span class="params">target,property,receiver</span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;target&#125;</span> is Getting <span class="subst">$&#123;property&#125;</span>`</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Reflect</span>.get(...arguments);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="function"><span class="title">set</span>(<span class="params">target,property,value,receiver</span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;target&#125;</span> is Setting <span class="subst">$&#123;property&#125;</span> to <span class="subst">$&#123;value&#125;</span>`</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Reflect</span>.set(...arguments);  </span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">proxy.name;         <span class="comment">// [object Object] is Getting name</span></span><br><span class="line">proxy.age = <span class="number">21</span>;     <span class="comment">// [object Object] is Setting age to 21 </span></span><br></pre></td></tr></table></figure>



<h4 id="9-3-2-隐藏属性"><a href="#9-3-2-隐藏属性" class="headerlink" title="9.3.2 隐藏属性"></a>9.3.2 隐藏属性</h4><p>使得<code>代码</code>对外部不可见</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> privateProperty = [<span class="string">&#x27;age&#x27;</span>,<span class="string">&#x27;sex&#x27;</span>,<span class="string">&#x27;addr&#x27;</span>]</span><br><span class="line"><span class="keyword">const</span> user = &#123;</span><br><span class="line">    <span class="attr">name</span>:<span class="string">&#x27;zyzc&#x27;</span>,</span><br><span class="line">    <span class="attr">age</span>:<span class="number">21</span>,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 将age设为不可见</span></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(user,&#123;</span><br><span class="line">    <span class="function"><span class="title">get</span>(<span class="params">target,property,receiver</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(privateProperty.includes(property))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">undefined</span>;</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">Reflect</span>.get(...arguments);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="function"><span class="title">has</span>(<span class="params">target,property,receiver</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(privateProperty.includes(property))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">Reflect</span>.has(...arguments);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(proxy.name);    <span class="comment">// zyzc</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy.age);     <span class="comment">// undefined</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;age&#x27;</span> <span class="keyword">in</span> proxy);<span class="comment">// false</span></span><br></pre></td></tr></table></figure>



<h4 id="9-3-3-属性验证"><a href="#9-3-3-属性验证" class="headerlink" title="9.3.3 属性验证"></a>9.3.3 属性验证</h4><p>使得设置属性的时候，判断是否允许赋值</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> target = &#123;</span><br><span class="line">    <span class="attr">name</span>:<span class="string">&#x27;zyzc&#x27;</span>,</span><br><span class="line">    <span class="attr">age</span>:<span class="number">21</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(target,&#123;</span><br><span class="line">    <span class="function"><span class="title">set</span>(<span class="params">target,property,value,receiver</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(property === <span class="string">&#x27;age&#x27;</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span>(<span class="keyword">typeof</span> value === <span class="string">&#x27;number&#x27;</span> )&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="built_in">Reflect</span>.set(...arguments);</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">proxy.age = <span class="string">&#x27;haha&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(proxy.age); <span class="comment">//  21</span></span><br><span class="line">proxy.age = <span class="number">22</span>;</span><br><span class="line"><span class="built_in">console</span>.log(proxy.age); <span class="comment">//  22</span></span><br></pre></td></tr></table></figure>



<h4 id="9-3-4-函数与构造函数参数验证"><a href="#9-3-4-函数与构造函数参数验证" class="headerlink" title="9.3.4 函数与构造函数参数验证"></a>9.3.4 函数与构造函数参数验证</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getMedian</span>(<span class="params">...nums</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> nums.sort()[<span class="built_in">Math</span>.floor(nums.length / <span class="number">2</span>)];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(getMedian, &#123;</span><br><span class="line">    <span class="function"><span class="title">apply</span>(<span class="params">target,thisArg,argumentsList</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">const</span> arg <span class="keyword">of</span> argumentsList) &#123;</span><br><span class="line">            <span class="keyword">if</span>(<span class="keyword">typeof</span> arg !== <span class="string">&#x27;number&#x27;</span>)&#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="string">&#x27;You should pass a Number&#x27;</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Reflect</span>.apply(...arguments);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(proxy(<span class="number">9</span>,<span class="number">8</span>,<span class="number">7</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>));        <span class="comment">// 7</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy(<span class="string">&quot;haha&quot;</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>));     <span class="comment">// You should pass a Number</span></span><br></pre></td></tr></table></figure>



<h4 id="9-3-5-数据绑定与观察"><a href="#9-3-5-数据绑定与观察" class="headerlink" title="9.3.5 数据绑定与观察"></a>9.3.5 数据绑定与观察</h4><blockquote>
<p>可以将被代理的类，绑定到一个全局实例集合中</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> userList = &#123;&#125;;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>._name = name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(User , &#123;</span><br><span class="line">    <span class="function"><span class="title">construct</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">const</span> newUser = <span class="built_in">Reflect</span>.construct(...arguments);</span><br><span class="line">        userList.push(newUser);</span><br><span class="line">        <span class="keyword">return</span> newUser;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> User(<span class="string">&#x27;zyzc1&#x27;</span>);</span><br><span class="line"><span class="keyword">new</span> User(<span class="string">&#x27;zyzc2&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(userList);	<span class="comment">// [ User &#123; _name: &#x27;zyzc1&#x27; &#125;, User &#123; _name: &#x27;zyzc2&#x27; &#125; ]</span></span><br></pre></td></tr></table></figure>

<p>还可以给集合绑定一个监听事件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> userList = [];    <span class="comment">// 具有内部属性 index、length，所以每次set的时候，都会遍历自定义属性和内部属性</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">emit</span>(<span class="params">newValue</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;你插入了&quot;</span>+newValue)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(userList , &#123;</span><br><span class="line">    <span class="function"><span class="title">set</span>(<span class="params">target,property,value,receiver</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">const</span> result = <span class="built_in">Reflect</span>.set(...arguments);</span><br><span class="line">        <span class="keyword">if</span>(result) &#123;</span><br><span class="line">            emit(<span class="built_in">Reflect</span>.get(target,property,receiver));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line">proxy.push(<span class="string">&#x27;zyzc1&#x27;</span>);	<span class="comment">// 你插入了：1 你插入了：zyzc1</span></span><br><span class="line">proxy.push(<span class="string">&#x27;zyzc2&#x27;</span>);	<span class="comment">// 你插入了：2 你插入了：zyzc2</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy)		<span class="comment">// [ &#x27;zyzc1&#x27;, &#x27;zyzc2&#x27; ]</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>为什么会多了一个1和2呢？我认为应该是在<code>if</code>里面，获取目标对象的属性时，会遍历其内部属性，如index或者length之类的，导致多出了1和2</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> userList = [];    </span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">emit</span>(<span class="params">newValue</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;你插入了：&quot;</span>+newValue)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(userList , &#123;</span><br><span class="line">    <span class="function"><span class="title">set</span>(<span class="params">target,property,value,receiver</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">const</span> result = <span class="built_in">Reflect</span>.set(...arguments);</span><br><span class="line">        <span class="keyword">if</span>(result) &#123;</span><br><span class="line">            <span class="keyword">let</span> temp = <span class="built_in">Reflect</span>.get(target,property,receiver);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;获取的目标对象是：&quot;</span>+target);       <span class="comment">// [&#x27;zyzc1&#x27;] [&#x27;zyzc1&#x27;] [&#x27;zyzc1&#x27;,&#x27;zyzc2&#x27;] [&#x27;zyzc1&#x27;,&#x27;zyzc2&#x27;]</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;获取的目标属性是：&quot;</span>+property);     <span class="comment">// 0         length    1		            length</span></span><br><span class="line">            <span class="comment">//emit();   </span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">proxy.push(<span class="string">&#x27;zyzc1&#x27;</span>);	<span class="comment">// 你插入了：1 你插入了：zyzc1</span></span><br><span class="line">proxy.push(<span class="string">&#x27;zyzc2&#x27;</span>);	<span class="comment">// 你插入了：2 你插入了：zyzc2</span></span><br><span class="line"><span class="built_in">console</span>.log(proxy);</span><br></pre></td></tr></table></figure>

<p>目前还没有想出有什么好的解释；</p>
</blockquote>
</blockquote>
<h3 id="9-4-小结"><a href="#9-4-小结" class="headerlink" title="9.4 小结"></a>9.4 小结</h3><ul>
<li>代理，开辟出JS的<code>元编程</code>及<code>抽象</code>的新区域</li>
<li>反射API，封装了一整套与捕获器拦截的操作相对应的方法，可以说是所有对象的API基础</li>
<li>代理与反射API，可以编写出类似于验证器、属性拦截器等模式。</li>
<li>听说vue3就是使用了代理来写dom的虚拟层的【后面学vue3原理的时候，再盘点一下】</li>
</ul>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2022/02/22/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E4%B9%9D%E7%AB%A0%EF%BC%9A%E4%BB%A3%E7%90%86%E4%B8%8E%E5%8F%8D%E5%B0%84/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript/" rel="tag">JavaScript</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2022/02/23/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E5%8D%81%E7%AB%A0%EF%BC%9A%E5%87%BD%E6%95%B0/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            《JavaScript高级程序设计》- 第十章：函数
          
        </div>
      </a>
    
    
      <a href="/2022/02/17/%E5%AF%92%E5%81%87/%E5%AF%92%E5%81%87%E8%AE%B0%E5%BD%95/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">寒假记录</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "jeb2pvxjdeJQOj5OG3AUavGv-gzGzoHsz",
    app_key: "6YlB9tQJTstHMM8GOwFu4uyY",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2022
        <i class="ri-heart-fill heart_icon"></i> 子与子乘
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="欢迎"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i></p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>